package cn.netty.exemple2;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

public class TimeClient {

    private NioEventLoopGroup requestGroup;
    private Bootstrap bootstrap;

    public void init(){
        this.requestGroup = new NioEventLoopGroup();
        this.bootstrap = new Bootstrap();
        this.bootstrap.group(requestGroup).channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY,true);
    }

    public TimeClient(){
        init();
    }

    public ChannelFuture doRequest(String host,int port) throws InterruptedException {

        this.bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            protected void initChannel(SocketChannel ch) throws Exception {

                //解决粘包问题 Handler放在执行链最下面
                ch.pipeline().addLast(new LineBasedFrameDecoder(1024))
                        .addLast(new StringDecoder())
                        .addLast(new TimeClientHandler());
            }
        });
        ChannelFuture future = this.bootstrap.connect(host, port).sync();

        return future;

    }

    public void shutDown(){
        this.requestGroup.shutdownGracefully();
    }


    public static void main(String[] args) {
        TimeClient client = new TimeClient();
        ChannelFuture future = null;
        try {
            future = client.doRequest("127.0.0.1", 8888);
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            System.out.println(e.getMessage());
        }finally {
            client.shutDown();
        }
    }
}
